namespace CloudApiServer;

using System;
using System.Security.Cryptography;
using System.Text;

public class AesCryptoHelper
{
    // AES-256-ECB 解密
    public static string DecryptInitInfo(string encryptedBase64, string hexKey)
    {
        byte[] encryptedData = Convert.FromBase64String(encryptedBase64);
        byte[] key = HexStringToByteArray(hexKey);

        using (Aes aes = Aes.Create())
        {
            aes.Key = key;
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.Zeros; // 或 PKCS7

            using (ICryptoTransform decryptor = aes.CreateDecryptor())
            {
                byte[] decrypted = decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
                return Encoding.UTF8.GetString(decrypted).TrimEnd('\0');
            }
        }
    }

    // AES-256-ECB 加密
    public static string EncryptInitInfo(string plainText, string hexKey)
    {
        byte[] key = HexStringToByteArray(hexKey);
        byte[] plainData = Encoding.UTF8.GetBytes(plainText);

        // 填充至 32 字节（AES-256 块大小）
        if (plainData.Length < 32)
        {
            byte[] paddedData = new byte[32];
            Buffer.BlockCopy(plainData, 0, paddedData, 0, plainData.Length);
            plainData = paddedData;
        }

        using (Aes aes = Aes.Create())
        {
            aes.Key = key;
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.None; // 手动填充

            using (ICryptoTransform encryptor = aes.CreateEncryptor())
            {
                byte[] encrypted = encryptor.TransformFinalBlock(plainData, 0, plainData.Length);
                return Convert.ToBase64String(encrypted);
            }
        }
    }

    // 16进制字符串转字节数组
    private static byte[] HexStringToByteArray(string hex)
    {
        int length = hex.Length;
        byte[] bytes = new byte[length / 2];
        for (int i = 0; i < length; i += 2)
        {
            bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        }
        return bytes;
    }
}